#include <nvs.h>
#include <nvs_flash.h>

char *Reboot_COUNT_KEY = "REBOOT_COUNT";

void write_reboot_count(nvs_handle_t nvs_handle, int8_t count)
{
    printf("update reboot count in NVS ... \n");
    esp_err_t err_ssid = nvs_set_i8(nvs_handle, Reboot_COUNT_KEY, count);
    printf((err_ssid != ESP_OK) ? "count Failed!\n" : "count Done\n");
}

void read_reboot_count(nvs_handle_t nvs_handle)
{
    int8_t count = -1;
    printf("read reboot count in NVS ... \n");
    esp_err_t err_count = nvs_get_i8(nvs_handle, Reboot_COUNT_KEY, &count);

    if (err_count == ESP_OK)
    {
        printf("Done\n");
        printf("READ NVS REBOOT COUNT: %d\n", count);
        if(count < 0) {
            count = 1;
        } else {
            count += 1;
        }
    }
    else
    {
        printf("Error (%s) reading!\n", esp_err_to_name(err_count));

        // default write count 1
        printf("NVS Write default reboot count 1");
    }
    write_reboot_count(nvs_handle, count);
}